package com.facebook.device.yearclass.slice;

import com.facebook.device.yearclass.ResourceTable;
import com.facebook.device.yearclass.YearClass;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

public class MainAbilitySlice extends AbilitySlice {
    private static final String PREF_FILE = "YearClass";
    private static final String PREF_NAME = "yearclass";
    private static final int MSG_UPDATE = 1;
    private Text mYearClass;
    private EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            switch (event.eventId) {
                case MSG_UPDATE:
                    mYearClass.setText(event.object + "");
                    break;
            }
        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mYearClass = (Text) findComponentById(ResourceTable.Id_text_helloworld);

        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(() -> {
            int yearClass = YearClass.CLASS_UNKNOWN;
            DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
            Preferences prefs = databaseHelper.getPreferences(PREF_FILE);
            if (prefs.hasKey(PREF_NAME)) {
                yearClass = prefs.getInt(PREF_NAME, YearClass.CLASS_UNKNOWN);
            }
            if (yearClass == YearClass.CLASS_UNKNOWN) {
                yearClass = YearClass.get(getApplicationContext());
                prefs.putInt(PREF_NAME, yearClass);
                prefs.flush();
            }

            InnerEvent event = InnerEvent.get(MSG_UPDATE, Integer.toString(yearClass));
            eventHandler.sendEvent(event);
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
